const Router = require("koa-router")
const fs = require("fs")
const path = require("path")

// 创建路由对象
const router = new Router();

router.get("/gee/getLocalFiles",async (ctx) => {
  // 获取请求参数
  const data = ctx.query;
  // 设置本地文件位置
  const loaclPath = data.path;
  // 保存文件地址
  const passPath = path.resolve(__dirname,'../')
  const targetPath = path.join(passPath,"/assets/files")
  // 读取本地文件，并将文件保存到项目本地assets/files中
  fs.readdir(loaclPath,(err,files) => {
    if(err) console.error("读取文件目录失败")
    files.forEach(item => {
      // 拼接文件保存前的地址
      const originFilePath = path.join(loaclPath,item)
      // 拼接文件保存后的地址
      const targetFilePath = path.join(targetPath,item)
      // 通过流将文件复制保存
      // 创建输入流和读取流
      const rs = fs.createReadStream(originFilePath)
      const ws = fs.createWriteStream(targetFilePath)
      // 通过管道将文件保存到ws中
      rs.pipe(ws);
      console.log("文件："+ item + "已经复制完毕")
    })
  })
  // 响应数据
  ctx.body = {
    data,
    loaclPath,
    targetPath
  }
})

router.get("/gee/getFilePath", async (ctx) => {
   // 保存文件地址
   const passPath = path.resolve(__dirname,'../')
   const targetPath = path.join(passPath,"/assets/files")
   const fileList = fs.readdirSync(targetPath)
  //  保存文件地址
  let filePathList = []
  let filePathList2 = []
   fileList.forEach(item => {
      const itemPath = path.join(targetPath,item)
      const suf = item.split(".")[1]
      filePathList.push({itemPath,suf});
      filePathList2.push({item,suf});
   })
   ctx.body = {
    filePathList,
    filePathList2,
    fileList
   }
})

router.get("/gee/getPath",async (ctx) => {
  // 文件地址
  const Tpath = ctx.query.path;
  const fileList = fs.readdirSync(Tpath)
  let newFileList = []
  let filePathList = []
   fileList.forEach(item => {
      const suf = item.split(".")[1]
      const filePath = "D:/桌面/热成像导出图像/" + item
      filePathList.push({filePath,suf});
      newFileList.push({item,suf})
   })
   ctx.body = {
    filePathList,
    fileList:newFileList
   }
})


// 导出router
module.exports = router;